import { showToast } from "../../utils/asyncWx";
import { getAddressInfo,deleteAddressOne,setAddressInfo} from "../../api/address.js";

Page({

    data: {
        address: []
    },

    onShow: function() {
        let userid= wx.getStorageSync('userid')
        console.log(userid);
        if(!userid){
            wx.switchTab({
                url: '/pages/user/index',
            })
             showToast({ title: "请先登录" });
        }else{
            this.getAddress();
        }
    },

    async getAddress() {
       let userid= wx.getStorageSync('userid')
        const address = await getAddressInfo(userid);
      console.log(address);
        this.setData({
            address: address
        })
    },

    handleChecked(e) {
        var userid = wx.getStorageSync('userid')
        const id = e.currentTarget.dataset.id;
        var address = this.data.address;
        address.map(async (v, index) => {
            v.isChecked = (v.id === id) ? true : false;
            const address = await setAddressInfo(v.id,v.isChecked)
        })
        this.getAddress();
    },

    async handleDelete(e) {
        const id = e.currentTarget.dataset.id;
        const userid = wx.getStorageSync('userid')
        console.log(userid);
        const address = await  deleteAddressOne(userid,id);
      this.getAddress();
    }
})